package com.pimee.service;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pimee.common.util.StringUtils;

import tk.mybatis.mapper.common.Mapper;

public class BaseService<T> implements IBaseService<T> {

	@Autowired
	protected Mapper<T> mapper;

	protected Logger logger = null;

	/**
	 * 设置请求分页数据
	 */
	protected Page<?> startPage(Map<String, Object> params) {
		Page<?> page = null;
		String pageNum = (String) params.get("pageNum");
		String pageSize = (String) params.get("pageSize");
		String orderBy = (String) params.get("orderBy");
		if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
			page = PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize), orderBy);
		}
		return page;
	}

	@Override
	public T selectByKey(Object key) {
		return (T) mapper.selectByPrimaryKey(key);
	}

	@Override
	public int save(T entity) {
		return mapper.insert(entity);
	}

	@Override
	public int saveNotNull(T entity) {
		return mapper.insertSelective(entity);
	}

	@Override
	public int deleteByKey(Object key) {
		return mapper.deleteByPrimaryKey(key);
	}

	@Override
	public int deleteBy(Object example) {
		return mapper.deleteByExample(example);
	}

	@Override
	public int updateAll(T entity) {
		return mapper.updateByPrimaryKey(entity);
	}

	@Override
	public int updateNotNull(T entity) {
		return mapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public int updateByExample(T entity, Object example) {
		return mapper.updateByExample(entity, example);
	}

	@Override
	public List<T> selectByExample(Object example) {
		return mapper.selectByExample(example);
	}

	@Override
	public int countByExample(Object example) {
		return mapper.selectCountByExample(example);
	}

	@Override
	public T selectOne(T entity) {
		return mapper.selectOne(entity);
	}

	@Override
	public T selectOneByExample(Object example) {
		return mapper.selectOneByExample(example);
	}

	@Override
	public List<T> listAll() {
		return mapper.selectAll();
	}

	public Mapper<T> getMapper() {
		return mapper;
	}
}
